home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1307 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: lrz-muenchen.de!sun2!ua302aa
  2. From: ua302aa@sun2.lrz-muenchen.de (Kurt Watzka)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: returning a string from a function
  5. Date: 12 Jan 1996 11:40:15 GMT
  6. Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
  7. Distribution: world
  8. Message-ID: <4d5hav$6mt@sparcserver.lrz-muenchen.de>
  9. References: <4d4uh8$q46@mailhost.mwmicro.com>
  10. NNTP-Posting-Host: sun2.lrz-muenchen.de
  11.  
  12. aschlies@citynet.net (Tony Schliesser) writes:
  13.  
  14. >I am learning C with the aid of only a book.  I am at an inpass in
  15. >this process.  I have a small function that needs to return a string
  16. >back to the main routine. I have the following prototype:
  17.  
  18. >char function_name(char in_string[80])
  19.  
  20. This function will return a char, not a pointer to char or an array of
  21. char. 
  22.  
  23. Since returning an array of char is probably not what you want, 
  24. returning a pointer to the first character of a string ('\0'-
  25. terminated sequence of characters) might be a good idea.
  26.  
  27. >{
  28. >    char value[80];
  29.  
  30. >    ...value takes on part of the value of the last 10 characters
  31. >      of in_string.
  32.  
  33. >    return(value);
  34.  
  35. 1) You should not return a pointer to an automatic object, and this
  36.    is what you are trying to do. A simple solution might be to
  37.    declare value as
  38.  
  39.      static char value[11];
  40.  
  41.    since you will need 11 chars to store the last 10 characters 
  42.    of a string as a string.
  43.  
  44. >}
  45.  
  46.  
  47. >jWhen this function is done, it only returns the first character.  I
  48. >"watched" the program execution and it shows that value indeed has the
  49. >last 10 characters.  Any clues as to why the calling routine only gets
  50. >the one character??
  51.  
  52. Because the function is defined to return a "char", not a "char *".
  53.  
  54. >Also, I wrote the routine that copies the last 10 characters. Is there
  55. >a lib. function that does that for me?? Did I reinvent the wheel?
  56.  
  57. Did you use strcpy()? AFAIK, there is no function that meets your
  58. specification in the standard C library.
  59.  
  60. Kurt
  61.  
  62.